from fastapi import FastAPI, HTTPException
import uvicorn
from pydantic import BaseModel
from typing import List

app = FastAPI(title="冒泡排序服务API")

class SortInput(BaseModel):
    array: List[int]
    ascending: bool = True

@app.post("/bubble_sort")
async def bubble_sort(input: SortInput):
    """执行冒泡排序算法"""
    if not input.array:
        raise HTTPException(status_code=400, detail="数组不能为空")
    
    arr = input.array.copy()
    n = len(arr)
    iterations = 0
    swaps = 0
    
    for i in range(n):
        swapped = False
        for j in range(0, n-i-1):
            iterations += 1
            if input.ascending:
                if arr[j] > arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                    swaps += 1
                    swapped = True
            else:
                if arr[j] < arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                    swaps += 1
                    swapped = True
        if not swapped:
            break
    
    return {
        "sorted_array": arr,
        "iterations": iterations,
        "swaps": swaps,
        "order": "ascending" if input.ascending else "descending"
    }

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)